<?php

namespace App\Http\Controllers\Home\User;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
use Crypt;
use Mail;
use session;
class UserController extends Controller
{
    //前台用户注册
    public function register(Request $request)
    {
    	
    	//此时验证出错时提示的英文,要把英文变成中文
	    $this->validate($request, [
	        'email' => 'required|email',
	        'password' => 'required|max:18|min:6',
	        'repassword' => 'required|same:password'
	    ],[
	        	'email.required' => '邮箱不能为空',
	            'email.email' => '邮箱格式不对',
	            'password.min' => '用户名最少6位',
	            'password.mix' => '用户名最多18位',
	            
	            'password.required' => '密码不能为空',
	            'repassword.required' => '确认密码不能为空',
	            'repassword.same' => '确认密码不一致'
	    ]);

	    //去除不需要的字段
    	$data = $request -> except('_token','repassword');

    	//密码加密
    	$password = $request -> password;
    	$data['password'] = Crypt::encrypt($data['password']);

    	//处理token字段
        $data['remember_token'] = str_random(50);

        //获取时间戳
        $time = time();

        //把注册时间放入数组
        $data['regtime'] = $time;

    	//把数据写入数据库
        $id = DB::table('users') -> insertGetId($data);
        $data['id'] = $id;
        if($id)
        {
            //成功,跳转到用户列表
            $res = DB::table('users_detail') -> insert(['uid' => $id, 'nickname' => $data['email']]);
            if($res)
            {
                $res = DB::table('address') -> insert(['uid' => $id]);
                if($res)
                {	
                	session(['master' => $data]);

                    return redirect('/home/index');
                }else
                {
                    DB::rollBack();
                    return back();
                }
                
            }else
            {
                DB::rollBack();
                return back();
            }
        }else
        {
            //失败跳回
            DB::rollBack();
            return back();
        }
    }

    //个人信息
    public function detail(Request $request)
    {   
        //获取信息
        $uid = session('master')['id'];
        $id = session('master')['id'];

        //获取详情表信息
        $data = DB::table('users_detail') ->  where('uid', $uid) -> first();
        //获取用户表信息
        $res = DB::table('users') -> where('id', $id) -> first();
        
        return view('home.user.user_detail', ['data' => $data, 'res' => $res]);
    }
    

    //修改个人信息
    public function edit(Request $request)
    {
        $uid = session('master')['id'];
        
        //取出信息
        $nickname = $request -> username;

        $birthday = $request -> birthday;
        $sex = $request -> sex;
        $realname = $request -> realname;
        $provice = $request -> resideprovince;
        $city = $request -> residecity;
        $area = $request -> address;
        $home = $request -> residecommunity;

        //获取旧的头像信息
        $res =  DB::table('users') -> select('pic') -> where('id', $uid) ->first();

        $oldpic = $res -> pic;

        $time = time();
        //写入数据
        $res = DB::table('users_detail') -> where('uid', $uid) -> update(['nickname' => $nickname, 'birthday' => $birthday, 'sex' => $sex, 'realname' => $realname, 'provice' => $provice, 'city' => $city, 'area' => $area, 'home' => $home]);

        if(!$res)
        {
            return back() -> with(['info' => '修改失败']);

        }

        //处理头像
        //判断文件是否上传
        if($request -> hasfile('pic'))
        {
            //判断文件是否有效
            if($request -> file('pic') ->isvalid())
            {   

                //获取图片后缀名
                $suffix = $request -> file('pic') -> getClientOriginalExtension();

                //为图片准备随机不重复的名称
                $fileName = $time.mt_rand(10000,99999). '.' .$suffix;

                //移动文件
                $move = $request -> file('pic') -> move('./uploads/portrait', $fileName);

                //判断是否移动成功
                if($move)
                {
                    //成功,改变pic的值,以便存入数据库
                    $data['newpic'] = $fileName;
                }
            }
        }else
        {
            return back() -> with(['info' => '文件上传失败']);
        }

        //把数据写入数据库
        $res = DB::table('users') -> where('id', $uid) -> update(['pic' => $data['newpic']] );

        if($res)
        {

            //判断文件是否存在
            if(file_exists('./uploads/portrait/'.$oldpic))
            {
                //判断文件是否是默认头像
                if($oldpic != 'default.jpg')
                {
                    //删除头像文件
                    $del = unlink('./uploads/portrait/'.$oldpic);
                    if($del)
                    {
                        return redirect('/home/user/detail') -> with(['info' => '修改成功']);
                    }
                }else
                {
                    return redirect('/home/user/detail') -> with(['info' => '修改成功']);
                }
            }else
            {
                return redirect('/home/user/detail') -> with(['info' => '数据已删除,头像文件未找到']);
            }
            //成功,跳转到用户列表
            return redirect('/home/user/detail');
        }else
        {
            //失败跳回
            return back();
        }
        
    }


    //修改密码
    public function password()
    {
       return view('/home/user/password');

    }

    //修改密码
    public function dopassword(Request $request)
    {

        //验证表单正确性
        $this->validate($request, [
        'newpassword' => 'required|max:18|min:6',
        'repassword' => 'required|same:newpassword'
        ],[
            'newpassword.required' => '新密码不能为空',
            'newpassword.min' => '密码最少6位',
            'newpassword.mix' => '密码最多18位',
            'repassword.required' => '确认密码不能为空',
            'repassword.same' => '确认密码不一致'
        ]);

        $id = session('master')['id'];

        //查询原密码
        $data = DB::table('users') -> where('id', $id) -> first();
        $oldpassword = Crypt::decrypt($data -> password);
        $oldpass = $request -> oldpass;
        $newpassword = $request -> newpassword;
        if($oldpass != $oldpassword)
        {
            return back() -> with(['info' => '原密码不正确']);
        }
        //新密码加密
        $newpass = Crypt::encrypt($newpassword);
        //存入新密码
        $res = DB::table('users') -> where('id', $id) -> update(['password' => $newpass]);
        if($res)
        {
            return redirect('home/user/password') -> with(['info' => '修改成功']);
        }else
        {
            return back() -> with(['info' => '修改失败']);
        }
    } 
    


    //找回密码
    public function retpassword(Request $request)
    {

        //获取信息
        $remail = $request['remail'];
        //判断邮箱是否存在
        $res = DB::table('users') -> where('email', $remail) -> first();
        //判断结果
        if(!$res)
        {
            return 0;
        }

        // Mail::raw('啦啦啦,德玛西亚', function($message){
        //     $message -> subject('这是一封来自异世界的信');
        //     $message -> to('nervqi@sina.com');
        // });
        //发送邮件
        $res = Mail::send('emails.forget', ['res' => $res], function($m) use ($remail){
            $m -> subject('这是一封来自异世界的信');
            $m -> to($remail);
        });

        //判断结果
        if($res)    
        {
            return 1;
        }else
        {
            return 2;
        }
    }


    //找回密码邮件跳回的连接
    public function resetpassword ($id, $remember_token)
    {
        $data = DB::table('users') -> where('id', $id) -> first();

        if($data -> remember_token != $remember_token)
        {
            return redirect('/home/forget/defeat');
        }else
        {
            return view('home.user.forget_win',['forgetpassword' => $data]);
        }
    }

    //找回密码失败
    public function defeat()
    {
        return view('home.user.forget_defeat');
    }

    //找回密码成功
    public function win(Request $request)
    {
        $this->validate($request, [
            'newpass' => 'required|max:18|min:6',
            'repass' => 'required|same:newpass'
        ],[               
                'newpass.min' => '用户名最少6位',
                'newpass.mix' => '用户名最多18位',                
                'newpass.required' => '密码不能为空',
                'repass.required' => '确认密码不能为空',
                'repass.same' => '确认密码不一致'
        ]);

        $data = $request -> except('_token','button');
        
        //密码加密
        $password = Crypt::encrypt($data['newpass']);

        //写入数据库
        $res = DB::table('users') -> where('id',$data['id']) -> update(['password' => $password]);

        if($res)
        {
            return redirect('home/index');
        }else
        {
            return back() -> with(['defeat' => '密码修改失败请再次尝试']);
        }
    }
}
